package com.example.demo.controller;

import com.example.demo.entity.Student;
import com.example.demo.repository.DepartmentRepository;
import com.example.demo.repository.StudentRepository;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@AllArgsConstructor
@RequestMapping("/students")
@RestController
public class StudentController {

    @Resource
    private final StudentRepository studentRepository;

    @Resource
    private final DepartmentRepository departmentRepository;

    @GetMapping("")
    public List<Student> students() {
        return studentRepository.findAll();
    }

    @GetMapping("/{id}")
    public Student getStudent(@PathVariable Integer id) {
        return studentRepository.findById(id).orElse(new Student());
    }

    @GetMapping("/lt/{age}")
    public List<Student> getYoungStudent(@PathVariable Integer age){
        return studentRepository.findByAgeBefore(age);
    }

    @GetMapping("/lta/{age}")
    public List<Student> getYoungStudentSorted(@PathVariable Integer age){
        return studentRepository.findByAgeBefore(age, Sort.by(Sort.Direction.ASC, "age"));
    }

    @PostMapping("")
    public Student newStudent(@RequestBody Student newStudent) {
        newStudent.setDept(departmentRepository.findById(newStudent.getDeptId()).get());
        return studentRepository.save(newStudent);
    }
}
